package queue_groups

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ QueueGroupsModel = (*customQueueGroupsModel)(nil)

type (
	// QueueGroupsModel is an interface to be customized, add more methods here,
	// and implement the added methods in customQueueGroupsModel.
	QueueGroupsModel interface {
		queueGroupsModel
		FindQueueGroup(ctx context.Context, deptid, roomid, doctorid string) (*QueueGroupsExt, error)
	}

	customQueueGroupsModel struct {
		*defaultQueueGroupsModel
	}
)

// NewQueueGroupsModel returns a model for the database table.
func NewQueueGroupsModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) QueueGroupsModel {
	return &customQueueGroupsModel{
		defaultQueueGroupsModel: newQueueGroupsModel(conn, c, opts...),
	}
}

// FindQueueGroup 获取分组信息
func (m *defaultQueueGroupsModel) FindQueueGroup(ctx context.Context, deptid, roomid, doctorid string) (*QueueGroupsExt, error) {
	callsystemQueueGroupsIdKey := fmt.Sprintf("%s%v", cacheCallsystemQueueGroupsIdPrefix, deptid+roomid+doctorid)
	var resp *QueueGroupsExt
	err := m.QueryRowCtx(ctx, &resp, callsystemQueueGroupsIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
		//query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", queueGroupsRows, m.table)
		query := fmt.Sprintf("SELECT * FROM callsystem.queue_groups where deptid= %s and rooms like %s and (doctorid = %s or doctorid is null) limit 1", queueGroupsRows, m.table)
		return conn.QueryRowCtx(ctx, v, query, deptid, roomid, doctorid)
	})
	switch err {
	case nil:
		return resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}
